package com.jiuyou.clientController.mall.cart;

import cn.hutool.Hutool;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.google.gson.JsonObject;
import com.jiuyou.clientController.base.ClientBaseController;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shopping.domain.MallProduct;
import com.ruoyi.shopping.domain.MallProductSpecs;
import com.ruoyi.shopping.domain.MallShoppingCart;
import com.ruoyi.shopping.service.IMallProductService;
import com.ruoyi.shopping.service.IMallProductSpecsService;
import com.ruoyi.shopping.service.IMallShoppingCartService;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chengliang
 * @date 2022/6/28
 **/
@RestController
@RequestMapping("/client/mall/cart")
public class MallShoppingCartClientController extends ClientBaseController {
    @Autowired
    private IMallShoppingCartService cartService;
    @Autowired
    private IMallProductSpecsService specsService;
    @Autowired
    private IMallProductService productService;

    @RequestMapping("/add")
    public AjaxResult add(MallShoppingCart cart){
        cart.setMemberId(getLoginMemberId());
        cart.setNum(1);
        MallShoppingCart c = cartService.selectMallShoppingCart(cart);
        if(null != c){
            c.setNum(c.getNum()+1);
            return AjaxResult.success(cartService.updateMallShoppingCart(c));
        }
        return AjaxResult.success(cartService.insertMallShoppingCart(cart));
    }
    @RequestMapping("/del")
    public AjaxResult del(MallShoppingCart cart){
        cart.setMemberId(getLoginMemberId());
        List<MallShoppingCart> list = cartService.selectMallShoppingCartList(cart);
        MallShoppingCart c = list.get(list.size() - 1);
        cartService.deleteMallShoppingCartById(c.getId());
        return AjaxResult.success();
    }
    @RequestMapping("/getCount")
    public AjaxResult getCount(){
        List<MallShoppingCart> list = cartService.selectCount(null, getLoginMemberId());
        Integer num = 0;
        for (MallShoppingCart cart : list) {
            num = cart.getNum()+num;
        }
        return AjaxResult.success(num);
    }
    @RequestMapping("/getSingleCount/{specsId}")
    public AjaxResult getSingleCount(@PathVariable Long specsId){
        return AjaxResult.success(cartService.selectCount(specsId,null));
    }
    @RequestMapping("/update")
    public AjaxResult getSingleCount(MallShoppingCart cart){
        return AjaxResult.success(cartService.updateMallShoppingCart(cart));
    }
    @RequestMapping("/flushSingle/{cartId}")
    public AjaxResult flushSingle(@PathVariable Long cartId){
        MallShoppingCart cart = cartService.selectMallShoppingCartById(cartId);
        MallProductSpecs specs = specsService.selectMallProductSpecsById(cart.getSpecsId());
        MallProduct product = productService.selectMallProductById(specs.getProductId());
        JSONObject jso = new JSONObject();
        jso.put("cartId",cart.getId());
        jso.put("productName",product.getProductName());
        String mainImg = specs.getSpecsPhoto();
        if(StringUtils.isEmpty(mainImg)){
            mainImg = product.getProductImage();
        }
        jso.put("mainImg",mainImg);

        jso.put("specsName",specs.getSpecsName());
        jso.put("specsId",specs.getId());
        jso.put("productId",product.getId());
        jso.put("canReset",false);
        Integer num = cart.getNum();
        jso.put("count",num);
//        BigDecimal multiply = specs.getCurrentPrice().multiply(new BigDecimal(num));
        jso.put("price",specs.getCurrentPrice());
        return AjaxResult.success(jso);
    }
    @RequestMapping("/getList")
    public AjaxResult getList(){
        startPage();
        MallShoppingCart cart = new MallShoppingCart();
        cart.setMemberId(getLoginMemberId());
        List<MallShoppingCart> cartList = cartService.selectMallShoppingCartList(cart);
        TableDataInfo dataTable = getDataTable(cartList);
        ArrayList<Map<Long, JSONObject>> maps = new ArrayList<>();
        if(cartList.size()>0){
            List<Long> collect = cartList.stream().map(MallShoppingCart::getSpecsId).collect(Collectors.toList());
            List<MallProductSpecs> specsList = specsService.selectListByIds(collect);

            ArrayList<Long> lapseIds = new ArrayList<>();
            //减除查询不到的商品(规格)
            specsList.forEach(e->{
                if(DicConstants.SYS_Y.getCode().equals(e.getDelState())){
                    lapseIds.add(e.getId());
                }
            });
            collect.removeAll(lapseIds);
            //由于商品被删除后一定会删除规格,差集的数据必定存在
            //获取剩余规格的商品
            collect.stream().distinct().forEach(e->{
                for (MallProductSpecs item:specsList) {
                    HashMap<Long, JSONObject> map = new HashMap<>();
                    if(e.equals(item.getId())){
                        MallProduct product = productService.selectMallProductById(item.getProductId());
                        JSONObject jso = new JSONObject();
                        jso.put("productName",product.getProductName());
                        String mainImg = item.getSpecsPhoto();
                        if(StringUtils.isEmpty(mainImg)){
                            mainImg = product.getProductImage();
                        }
                        jso.put("mainImg",mainImg);
                        jso.put("specsName",item.getSpecsName());
                        jso.put("specsId",item.getId());
                        jso.put("productId",product.getId());
                        jso.put("canReset",false);

                        for (MallShoppingCart mallShoppingCart : cartList) {
                            if(mallShoppingCart.getSpecsId().equals(e)){
                                Integer num = mallShoppingCart.getNum();
                                jso.put("count",num);
//                                BigDecimal multiply = item.getCurrentPrice().multiply(new BigDecimal(num));
                                jso.put("price",item.getCurrentPrice());
                                jso.put("cartId",mallShoppingCart.getId());
                                break;
                            }
                        }
//                    jso.put("count",cartList.stream().filter(a->Objects.equals(a.getId(),e)).findFirst().get().getNum());
                        jso.put("lapse",false);
                        jso.put("finished",dataTable.isLastPage());
                        map.put(product.getId(),jso);
                        maps.add(map);
                    }
                }
            });
            //失效商品
        }
        return AjaxResult.success(maps);
    }

    @RequestMapping("/getLapseList")
    public AjaxResult getLapseList(){
        MallShoppingCart cart = new MallShoppingCart();
        cart.setMemberId(getLoginMemberId());
        List<MallShoppingCart> cartList = cartService.selectMallShoppingCartList(cart);
        ArrayList<Map<Long, JSONObject>> maps = new ArrayList<>();
        if(cartList.size()>0){
            List<Long> collect = cartList.stream().map(MallShoppingCart::getSpecsId).collect(Collectors.toList());
            List<MallProductSpecs> specsList = specsService.selectListByIds(collect);
            ArrayList<Long> lapseIds = new ArrayList<>();
            //减除查询不到的商品(规格)
            specsList.forEach(e->{
                if(DicConstants.SYS_Y.getCode().equals(e.getDelState())){
                    lapseIds.add(e.getId());
                }
            });
//        collect.retainAll(lapseIds);
            lapseIds.stream().distinct().forEach(e->{
                for (MallProductSpecs item:specsList) {
                    HashMap<Long, JSONObject> map = new HashMap<>();
                    if(e.equals(item.getId())){
                        MallProduct product = productService.selectMallProductById(item.getProductId());
                        JSONObject jso = new JSONObject();
                        jso.put("productName",product.getProductName());
                        jso.put("mainImg",product.getProductImage());
//                    jso.put("price",item.getCurrentPrice());
//                    jso.put("specsName",item.getSpecsName());
//                    jso.put("specsId",item.getId());
//                    jso.put("productId",product.getId());
//                    jso.put("count",0);
//                    jso.put("lapse",true);
//                    map.put(product.getId()+1000,jso);
                        for (MallShoppingCart mallShoppingCart : cartList) {
                            if(mallShoppingCart.getSpecsId().equals(e)){
                                jso.put("cartId",mallShoppingCart.getId());
                                break;
                            }
                        }
//                    if(DicConstants.SYS_Y.getCode().equals(product.getIsShow())){
//                        jso.put("canReset",true);
//                    }
                        maps.add(map);
                    }
                }
            });
        }

        return AjaxResult.success(maps);
    }
    @RequestMapping("/clear")
    public AjaxResult clear(String ids){
        Long[] longs = Convert.toLongArray(StringUtils.split(ids,","));
        cartService.deleteMallShoppingCartByIds(longs);
        return AjaxResult.success();
    }

}
